package com.io.commoncontrol

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView

/**
 * Description:圆角按钮-可以设置背景色、指定圆角、描边的宽度和颜色的按钮
 * 2021-04-29 17:34
 * @author LiuMin
 */
class RoundButton : AppCompatTextView {
    private var roundButtonDrawable: RoundButtonDrawable? = null

    constructor(context: Context) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(
        context,
        attrs,
        R.attr.RoundButtonStyle
    ) {
        init(context, attrs, R.attr.RoundButtonStyle)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context, attrs, defStyleAttr)
    }

    /**
     * 设置背景颜色
     */
    override fun setBackgroundColor(color: Int) {
        roundButtonDrawable?.setColor(color)
    }

    /**
     * 设置描边的宽度和颜色
     */
    fun setStrokeData(width: Int, color: Int) {
        roundButtonDrawable?.setStrokeData(width, color)
    }

    /**
     * 设置描边颜色
     */
    fun setStrokeColors(color: Int) {
        roundButtonDrawable?.setStrokeColor(color)
    }

    /**
     * 设置四个角的半径
     */
    fun setRadius(radius: Int) {
        roundButtonDrawable?.cornerRadius = radius.toFloat()
    }

    fun setEachCornerRadius(
        topLeftRadius: Int,
        topRightRadius: Int,
        bottomLeftRadius: Int,
        bottomRightRadius: Int
    ) {
        val radius = floatArrayOf(
            topLeftRadius.toFloat(),
            topLeftRadius.toFloat(),
            topRightRadius.toFloat(),
            topRightRadius.toFloat(),
            bottomLeftRadius.toFloat(),
            bottomLeftRadius.toFloat(),
            bottomRightRadius.toFloat(),
            bottomRightRadius.toFloat()
        )
        roundButtonDrawable?.cornerRadii = radius
    }

    /**
     * 设置渐变
     */
    fun setGradient(
        gradientType: Int,
        orientation: GradientDrawable.Orientation,
        colors: IntArray
    ) {
        roundButtonDrawable?.gradientType = gradientType
        roundButtonDrawable?.orientation = orientation
        roundButtonDrawable?.colors = colors
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        attrs?.let {
            roundButtonDrawable = RoundButtonDrawable.fromAttrSet(context, attrs, defStyleAttr)
            setBackgroundKeepingPadding(this, roundButtonDrawable)
        }
    }

    fun setBackgroundKeepingPadding(view: View, drawable: Drawable?) {
        val padding =
            intArrayOf(view.paddingLeft, view.paddingTop, view.paddingRight, view.paddingBottom)
        drawable?.let {
            view.background = drawable
        }
        view.setPadding(padding[0], padding[1], padding[2], padding[3])
    }
}